import random
import string

from flask import Blueprint, render_template, request, session, jsonify, redirect,url_for,g,flash,current_app
import os
from flask_mail import Message
from sqlalchemy.testing.suite.test_reflection import users
from werkzeug.security import generate_password_hash, check_password_hash
from werkzeug.utils import secure_filename

from ..decorators import login_required
from ..exts import mail,db
from app.models import UserModel,EmailCaptchaModel
from .forms import RegisterForm,LoginForm

bp=Blueprint('auth',__name__,url_prefix='/auth',template_folder='../templates/end')

@bp.route('/login',methods=['GET','POST'])
def login():
    if request.method=='GET':
        return render_template('login.html')
    else:
        form=LoginForm(request.form)
        if form.validate():
            email=form.email.data
            password=form.password.data
            user=UserModel.query.filter_by(email=email).first()
            if user:
                #核对密码
                if check_password_hash(user.password,password):
                    session['user_id']=user.id
                    return redirect('/end')
                else:
                    print('密码错误！！！')
                    return redirect(url_for('auth.login'))
            else:
                print('该用户不存在')
                return redirect(url_for('auth.login'))
        else:
            return redirect(url_for('auth.login'))

@bp.route('/logout')
def logout():
    session.clear()
    return redirect('/')


@bp.route('/detail')
def detail():
    return render_template('base.html')

@bp.route('/register',methods=['GET','POST'])
# @login_manager.user_loader
def register():
    if request.method=='GET':
        return render_template('register.html')
    else:
        # 表单验证
        form=RegisterForm(request.form)
        if form.validate():
            email=form.email.data
            username=form.username.data
            password=form.password.data
            user=UserModel(username=username,password=generate_password_hash(password),email=email)
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('auth.login'))
        else:
            print(form.errors)
            return redirect(url_for('auth.register'))


@bp.route('/captcha/email')
def get_email_captcha():
    email=request.args.get('email')
    source=string.digits*6
    captcha=random.sample(source,6)
    captcha=''.join(captcha)
    message=Message('LIKT安全博客系统注册邮箱验证码',recipients=[f'{email}'],body=f'LIKT安全博客系统注册邮箱验证码为：{captcha}，该验证码一分钟内有效！！！')
    mail.send(message)
    email_captcha=EmailCaptchaModel(email=email,captcha=captcha)
    db.session.add(email_captcha)
    db.session.commit()
    return jsonify({"code":200,"message":'',"data":None})


@bp.route('/updatePassword')
def update_password():
    return '1'

@bp.route('/mysetting')
def mysetting():
    user=g.user
    return render_template('mysetting.html',user=user)

@bp.route('/updateProfile', methods=['GET', 'POST'])
@login_required
def update_profile():
    if request.method == 'GET':
        return render_template('mysetting.html', user=g.user)  # 明确传 user

    user = g.user
    user.username = request.form.get('username')
    user.email = request.form.get('email')
    user.job = request.form.get('job')
    user.profile = request.form.get('profile')

    avatar_file = request.files.get('mypic')
    if avatar_file and avatar_file.filename:
        filename = secure_filename(avatar_file.filename)
        file_path = os.path.join(current_app.config['COVER_FOLDER'], filename)
        avatar_file.save(file_path)
        user.avatar = f'uploads/covers/{filename}'

    try:
        db.session.commit()
        flash('资料更新成功', 'success')
    except Exception as e:
        db.session.rollback()
        flash('更新失败，请重试', 'danger')
        print(f'更新用户信息出错：{e}')

    return redirect(url_for('auth.update_profile'))



@bp.route('/sysSetting')
def sys_setting():
    return render_template('sysSetting.html')

@bp.route('/blogMember')
def blog_member():
    members=UserModel.query.order_by(UserModel.join_time.asc()).all()
    return render_template('blogMember.html',members=members)

@bp.route('/addMember')
def add_member():#添加博客成员
    return render_template('blogMember.html')

@bp.route('/editMember')
def edit_member():
    return '1'

@bp.route('/deleteMember')
def delete_member():
    return '1'

@bp.route('/disableMember')
def disable_member():
    return '1'


@bp.route('/searchMember',methods=['GET','POST'])
def search_member():
    if request.method=='POST':
        username=request.form.get('username','').strip()
        job=request.form.get('job','').strip()
        search=request.form.get('search')
        if search=='member':
            querymember=UserModel.query
            if username:
                querymember=querymember.filter(UserModel.username.ilike(f'%{username}%'))
            if job:
                querymember=querymember.filter(UserModel.job.ilike(f'%{job}%'))
            members=querymember.order_by(UserModel.join_time.asc()).all()
            return render_template('blogMember.html',members=members)

